# coding=utf-8
"""

"""
import subprocess

import requests

from main import SHARE_FOLDER
from main.do_utils import local_ip, sql_log


# @Time    :  2024-06-06 12:22:09
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  mysql_backup
# @File    :  do_share


# 局域网 websocket 分享 :
def share(port: int = 8000):
    """
    自动获取本机 IP 地址
    如果获取不到, 就使用参数定义的 IP 地址
    """

    def is_http_server_running(server_ip, server_port):
        try:
            response = requests.get(f'http://{server_ip}:{server_port}')
            # 如果返回状态码为200，说明服务器正在运行
            return response.status_code == 200
        except requests.ConnectionError:
            # 如果连接错误，说明服务器未运行
            return False

    _ip = local_ip

    if is_http_server_running(_ip, port):
        sql_log.info('http server 运行中, 无需创建')
    else:
        sql_log.info('http server 创建成功')
        subprocess.run(["python", "-m", "http.server", str(port), "--bind", _ip, "--directory", SHARE_FOLDER])


if __name__ == '__main__':
    share()
